package com.jqb.jsplab.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.jqb.jsplab.dao.IStudentDao;
import com.jqb.jsplab.vo.Student;

public class StudentDaoImpl implements IStudentDao {

	private Connection conn = null;
	PreparedStatement pstmt = null;

	public StudentDaoImpl(Connection conn) {
		this.conn = conn;
	}

	/**
	 * 验证登录
	 * */
	@Override
	public boolean isLogin(String name, String password) throws Exception {
		String sql = "select id, name,password from jsp01_student where name=?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, name);
		ResultSet rs = pstmt.executeQuery();
		if (rs.next()) {
			String rpassword = rs.getString("password");
			if (rpassword.equals(password)) {
				return true;
			}
			return false;
		} else {
			return false;
		}
	}

	/**
	 * 通过ID查找学生信息
	 * */
	@Override
	public Student findStudentById(int id) throws Exception {
		String sql = "select id, name from jsp01_student where id=?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, id);
		ResultSet rs = pstmt.executeQuery();
		Student student = null;
		if (rs.next()) {
			student = new Student();
			student.setId(Integer.parseInt(rs.getString("id")));
			student.setName(rs.getString("name"));
		}
		pstmt.close();
		return student;
	}

	/**
	 * 通过姓名判断是否已存在
	 * */
	@Override
	public boolean isStudentExist(String name) throws Exception {
		String sql = "select id from jsp01_student where name = ?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, name);
		ResultSet rs = pstmt.executeQuery();
		boolean flag = false;
		if (rs.next()) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 新增学生
	 * */
	@Override
	public boolean createStudent(Student student) throws Exception {
		boolean flag = false;
		String sql = "insert into jsp01_student(name,password)values(?,?)";
		String name = student.getName();
		String password = student.getPassword();
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, name);
		pstmt.setString(2, password);
		int i = pstmt.executeUpdate();
		if (i > 0) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 返回所有用户id
	 * */
	@Override
	public int[] findStudentId() throws Exception {
		String sql = "select id from jsp01_student";
		pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
		ResultSet rs = pstmt.executeQuery();
		int id[] = null;
		if (rs.next()) {
			rs.last();
			int len = rs.getRow();
			id = new int[len];
			rs.beforeFirst();
			int i = 0;
			while (rs.next()) {
				id[i] = rs.getInt("id");
				i++;
			}
		}
		return id;
	}

}
